package com.taptech.doufu.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.FileUtil2;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.util.UIUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

/**
 * Created by lsy on 2015/7/28.
 */
public class NewFullScreenImageActivity extends DiaobaoBaseActivity implements View.OnClickListener {

    public static final int FINISH_ACTIVITY = 1001;

    // ui控件
    ViewPager mImgViewPager;
    TextView mImgNumTextView;
    ImageView mImgDownloadBtn;
    // 子ui控件
    RelativeLayout mPagerLayout;
    ImageView imageView;
    SimpleDraweeView gifImageView;
    View blockView;
    // 数据
    LinkedHashSet<String> mImagesUrl;
    LinkedHashSet<String> mOriginImagesUrl;
    List<Integer> mImageHeights;
    List<Integer> mImageWidths;
    List<View> mImageViewList;
    // 图片url数据
    List<String> imgUrlList;
    int mPosition = 0;
    private boolean mAbleToDownload;
    private ImageView placeHolderImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.full_screen_image_activity_layout);
        initView();
        initData();
        initViewPager(mImagesUrl.size());
    }

    private void initViewPager(final int totalNum) {
        imgUrlList = new ArrayList<String>(mImagesUrl);

        for (int i = 0; i < totalNum; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.new_full_screen_image_layout, mImgViewPager, false);


            mImageViewList.add(view);
        }
        mImgViewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return totalNum;
                //return 0;
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mImageViewList.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int i) {
                container.addView(mImageViewList.get(i));
                View view = mImageViewList.get(i);
                mPagerLayout = (RelativeLayout) view.findViewById(R.id.new_full_screen_layout);
                mPagerLayout.setOnClickListener(NewFullScreenImageActivity.this);
                imageView = (ImageView) view.findViewById(R.id.full_screen_item_image);
                placeHolderImg = (ImageView) view.findViewById(R.id.place_holder_img);
                /*BitmapFactory.Options options = new BitmapFactory.Options();
                options.outHeight
                Bitmap bm = BitmapFactory.decodeResource(getResources() , R.drawable.note_deafault_loading_img , )*/
                imageView.setOnClickListener(NewFullScreenImageActivity.this);
                gifImageView = (SimpleDraweeView) view.findViewById(R.id.full_screen_item_gif);
                final String urlHead = "http://imgold2.doufu.la/";
                if (DiaobaoUtil.isImageUrlGif(urlHead + imgUrlList.get(i))) {
                    gifImageView.setVisibility(View.VISIBLE);
                    mImageViewList.get(i).setClickable(true);
                    mImageViewList.get(i).setOnClickListener(NewFullScreenImageActivity.this);
                    imageView.setVisibility(View.GONE);
                    ImageManager.loadGifImage(gifImageView, urlHead + imgUrlList.get(i), mImageWidths.get(i) / (float) mImageHeights.get(i), new BaseControllerListener<ImageInfo>() {
                    });
                } else {
                    gifImageView.setVisibility(View.GONE);
                    imageView.setVisibility(View.VISIBLE);
                    //imageView.setImageResource(R.drawable.note_deafault_loading_img);
                    if (placeHolderImg != null){
                        //placeHolderImg.setVisibility(View.VISIBLE);
                    }
                    ImageManager.displayImageToFullWidth(imageView , imgUrlList.get(i) , handler);
                    /*ImageManager.displayImage(imageView, urlHead + imgUrlList.get(i), ImageManager.bigPhotooptions, new NetworkImageResListener() {
                        @Override
                        public void loadComplete(Bitmap bitmap) {
                            //placeHolderImg.setVisibility(View.GONE);
                            *//*PhotoViewAttacher photoViewAttacher = new PhotoViewAttacher(imageView);
                            photoViewAttacher.setmHandler(handler);*//*
                        }

                        @Override
                        public void loadComplete(String imageUri, View view, Bitmap loadedImage) {
                            PhotoViewAttacher photoViewAttacher = new PhotoViewAttacher((ImageView) view);
                            photoViewAttacher.setmHandler(handler);
                        }
                    });*/

                }
                return mImageViewList.get(i);
            }
        });
        mImgViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mImgNumTextView.setText(position + 1 + "/" + mImagesUrl.size());
                mPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        if (mPosition >= 0) {
            mImgViewPager.setCurrentItem(mPosition);
        }
        TTLog.d("tag", "viewpager position ======================" + mPosition);
    }

    private void initData() {
        Intent intent = getIntent();
        mImagesUrl = (LinkedHashSet<String>) intent.getSerializableExtra(Constant.LIST);
        mOriginImagesUrl = (LinkedHashSet<String>) intent.getSerializableExtra(Constant.IMAGE);
        mImageHeights = (ArrayList<Integer>) intent.getSerializableExtra(Constant.HEIGHT);
        mImageWidths = (List<Integer>) intent.getSerializableExtra(Constant.WIDTH);
        mPosition = intent.getIntExtra(Constant.ARTICLE_ITEM, 0);
        mImgNumTextView.setText((mPosition + 1) + "/" + mImagesUrl.size());
        mImageViewList = new ArrayList<View>();

        mAbleToDownload = intent.getBooleanExtra(Constant.ABLE_TO_DOWNLOAD, false);
        if (mAbleToDownload) {
            mImgDownloadBtn.setImageResource(R.drawable.download_draw_and_cos_img);
            mImgDownloadBtn.setTag("true");
        } else {
            mImgDownloadBtn.setImageResource(R.drawable.not_download_draw_and_cos_img);
            mImgDownloadBtn.setTag("false");
        }


    }

    private void initView() {
        mImgNumTextView = (TextView) findViewById(R.id.photo_group_page);
        mImgViewPager = (ViewPager) findViewById(R.id.big_img_view_pager);
        mImgDownloadBtn = (ImageView) findViewById(R.id.img_download_btn);
    }


    public void saveImage(View view) {
        String tempTag = mImgDownloadBtn.getTag().toString();
        if (tempTag != null && tempTag.equals("true")) {
            List<String> imagesUrls = new ArrayList<String>(mOriginImagesUrl);
            TTLog.d("tag", "下载页position ======================" + mPosition);
            String url = "http://imgold2.doufu.la/" + imagesUrls.get(mPosition);
            Toast toast;
        /*if (url.endsWith(".gif")) {
            toast = Toast.makeText(this, "下载成功，图片已保存至:" + Constant.AppDir.DIR_HOME + url.hashCode() + ".gif", Toast.LENGTH_LONG);
            FileUtil2.copyFile(ImageManager.getCacheFilePath(url), Constant.AppDir.DIR_HOME + url.hashCode() + ".gif");
        } else {
            toast = Toast.makeText(this, "下载成功，图片已保存至:" + Constant.AppDir.DIR_HOME + url.hashCode() + ".jpg", Toast.LENGTH_LONG);
            FileUtil2.copyFile(ImageManager.getCacheFilePath(url), Constant.AppDir.DIR_HOME + url.hashCode() + ".jpg");
        }*/

            toast = Toast.makeText(this, "正在下载", Toast.LENGTH_SHORT);
            File file = new File(Constant.AppDir.DIR_HOME);

            if (!file.exists()) {
                file.mkdir();
            }
            if (DiaobaoUtil.isImageUrlGif(url)){
                FileUtil2.saveImageAsFile(this, Constant.AppDir.DIR_HOME + url.hashCode(), url ,  true);
            }else {
                //ImageManager.saveImage(this , Constant.AppDir.DIR_HOME + url.hashCode() + ".jpg" , url , false);
                FileUtil2.saveImageAsFile(this, Constant.AppDir.DIR_HOME + url.hashCode() + ".jpg", url);
            }

            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();

        } else {
            UIUtil.toastMessage(NewFullScreenImageActivity.this, "作品保护已开启");

        }

    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case FINISH_ACTIVITY:
                    finish();
                    break;
            }
        }
    };

    public void back(View view) {
        finish();
    }

    @Override
    public void onClick(View view) {

        finish();


    }
}

